package com.tongguan.paypos.fragment;

import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.tongguan.paypos.R;
import com.tongguan.paypos.activity.trans.PayTypeSelectActivity;
import com.tongguan.paypos.base.BaseFragment;
import com.tongguan.paypos.common.AppConstants;
import com.tongguan.paypos.common.RequestCallback;
import com.tongguan.paypos.common.UrlConstants;
import com.tongguan.paypos.common.User;
import com.tongguan.paypos.entity.PayInfo;
import com.tongguan.paypos.entity.QRCodeInfo;
import com.tongguan.paypos.entity.TransInfo;
import com.tongguan.paypos.interfaces.JumpAct;
import com.tongguan.paypos.utils.Arith;
import com.tongguan.paypos.utils.L;
import com.tongguan.paypos.utils.ToastUtils;
import com.tongguan.paypos.view.CustomAlertDialog;
import com.uuzuche.lib_zxing.activity.CodeUtils;

import java.text.NumberFormat;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Call;

/**
 * Created by Joylive on 2017/1/4 .
 */

public class QRCodeWxFragment extends BaseFragment {
    @BindView(R.id.txt_integer)
    TextView mTxtInteger;
    @BindView(R.id.txt_decimal)
    TextView mTxtDecimal;
    @BindView(R.id.ll_money)
    LinearLayout mLlMoney;
    @BindView(R.id.iv_qr_code)
    ImageView mIvQrCode;
    private static final int DELAYED_TIME = 5 * 1000;//查询间隔
    private static final int FIRST_TIME = 12 * 1000; //首次查询时间
    private int count;//查询次数
    private JumpAct jumpAct;
    private double money;
    private String orderId;
    private String url;
    private boolean isClose = false;
    private boolean isDestroy = false;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_qrcodes_wx_pay, container, false);
        ButterKnife.bind(this, rootView);
        Bundle arguments = getArguments();
        if (arguments != null) {
            money = arguments.getDouble(PayTypeSelectActivity.MONEY);
            L.d(money + "  ");
        }
        initData();
        isDestroy = false;//还原状态
        count =10;
        return rootView;
    }

    private void initData() {
        if (TextUtils.isEmpty(url)) {
            params = new HashMap<>();
            params.put(UrlConstants.KEY_ACCOUNT, User.getInstance().getAccount());
            params.put(UrlConstants.KEY_POS_ID, User.getInstance().getPosId());
            params.put(UrlConstants.KEY_COUPON_MONEY, 0);
            params.put(UrlConstants.KEY_COUPON_INFO, "");
            params.put(UrlConstants.KEY_PAY_MONEY, String.valueOf(money));
            params.put(UrlConstants.KEY_CHANNEL_ID, "WX");
            RequestCallback.post(frmCtx, UrlConstants.QR_CODE_MAIN_PAY, params, mDialog, new AbstractRequestCallback() {
                @Override
                public void onResponse(String response, int id) {
                    QRCodeInfo qrCodeInfo = QRCodeInfo.objectFromData(response);
                    if (qrCodeInfo.getStatus() != 100) {
                        ToastUtils.showCustom(frmCtx, qrCodeInfo.getMessage());
                        mIvQrCode.setVisibility(View.GONE);
                        return;
                    }
                    orderId = qrCodeInfo.getOrderId();
                    url = qrCodeInfo.getCodeUrl();
                    saveImgCache(url);
                    mHandler.sendEmptyMessageDelayed(0, FIRST_TIME);
                }
            });
        }else {
            if (TextUtils.isEmpty(orderId)||TextUtils.isEmpty(url)||money==0){
                return;
            }
            saveImgCache(url);
            mHandler.sendEmptyMessageDelayed(0, FIRST_TIME);
        }
    }

    private void saveImgCache(String url) {
        Bitmap bitmap = CodeUtils.createImage(url, 400, 400, BitmapFactory.decodeResource(getResources(), R.drawable.ic_qr_wx_show));
        mIvQrCode.setImageBitmap(bitmap);
        mLlMoney.setVisibility(View.VISIBLE);
        changeContent(String.valueOf((long) Arith.mul(money, 100)));
    }

    private void changeContent(String total) {
        int length = total.length();
        if (length < 3) {
            if (length < 2) {
                String temp = "0" + total.toString();
                mTxtDecimal.setText(temp);
                if (length == 0) {
                    mTxtDecimal.setText(R.string.money_unit_3);
                }
            } else {
                mTxtDecimal.setText(total.toString());
            }
            mTxtInteger.setText(R.string.money_unit_1);
        } else {
            NumberFormat format = NumberFormat.getNumberInstance();
            mTxtInteger.setText(format.format(Double.parseDouble(total.substring(0, length - 2))));
            mTxtDecimal.setText(total.subSequence(length - 2, length));
        }
    }

    private void queryOder() {
        params = new HashMap<>();
        params.put(UrlConstants.KEY_ACCOUNT, User.getInstance().getAccount());
        params.put(UrlConstants.KEY_POS_ID, User.getInstance().getPosId());
        params.put(UrlConstants.KEY_ORDER_ID, orderId);
        RequestCallback.post(frmCtx, UrlConstants.QUERY_ORDER, params, new RequestCallback.HttpCallback() {
            @Override
            public void onResponse(String response, int id) {
                PayInfo payInfo = PayInfo.objectFromData(response);
                String message = payInfo.getMessage();
                if (payInfo.getStatus() != 100) {
                    //查询状态还是失败 继续查询
                    if (AppConstants.messageFilter(message)) { // 问题拦截
                        new CustomAlertDialog.Builder(frmCtx).setTitle(R.string.common_tip_title)
                                .setMessage(message)
                                .setPositiveButton(R.string.common_sure, (dialog, which) -> {})//finish
                                .show();
                        return;
                    }
                    mHandler.sendMessageDelayed(mHandler.obtainMessage(0, message), DELAYED_TIME);
                    return;
                }
                if (!"0".equals(payInfo.getState())) {
                    //查询上游 订单
                    mHandler.sendMessageDelayed(mHandler.obtainMessage(0, message), DELAYED_TIME);
                    return;
                }
                TransInfo transInfo = payInfo.getTransInfo();
                if (transInfo == null) {
                    //查询详情
                    queryOderDetail();
                    return;
                }
                if (mDialog != null && mDialog.isShowing()) {
                    mDialog.dismiss();
                }
                //成功跳转
                successJumpAct(transInfo, payInfo.getWxImgUrl());
            }

            @Override
            public void onError(Call call, Exception e, int id) {
                mHandler.sendMessageDelayed(mHandler.obtainMessage(0, "查询订单网络异常"), DELAYED_TIME);
            }
        });
    }

    /**
     * 查询订单详情接口
     */
    private void queryOderDetail() {
        params = new HashMap<>();
        params.put(UrlConstants.KEY_ACCOUNT, User.getInstance().getAccount());
        params.put(UrlConstants.KEY_POS_ID, User.getInstance().getPosId());
        params.put(UrlConstants.KEY_ORDER_ID, orderId);
        RequestCallback.post(frmCtx, UrlConstants.ORDER_DETAILS + orderId, params, new AbstractRequestCallback() {
            @Override
            public void onResponse(String response, int id) {

                PayInfo payInfo = PayInfo.objectFromData(response);
                if (payInfo.getStatus() != 100) {
                    ToastUtils.showCustom(frmCtx, payInfo.getMessage());
                    return;
                }
                TransInfo transInfo = payInfo.getTransInfo();
                if (transInfo == null) {
                    new CustomAlertDialog.Builder(frmCtx).setTitle(R.string.common_tip_title)
                            .setMessage(payInfo.getMessage() + "\n订单详情查询失败，是否重新请求")
                            .setPositiveButton(R.string.common_sure, (dialog, which) -> queryOderDetail())
                            .setNegativeButton(R.string.common_cancel, null).show();
                    return;
                }
                if (!"0".equals(transInfo.getState())) {
                    //防止数据查询接口和订单详情接口没同步
                    new CustomAlertDialog.Builder(frmCtx).setTitle(R.string.common_tip_title)
                            .setMessage("详情状态错误"+transInfo.getState())
                            .setPositiveButton(R.string.common_sure, (dialog, which) -> queryOderDetail())
                            .setNegativeButton(R.string.common_cancel, null).show();
                }
                //成功跳转
                successJumpAct(transInfo, payInfo.getWxImgUrl());
            }

            @Override
            public void onError(Call call, Exception e, int id) {
                super.onError(call, e, id);
                new CustomAlertDialog.Builder(frmCtx).setTitle(R.string.error_net)
                        .setMessage(e.getMessage())
                        .setPositiveButton("重新加载", (dialog, which) -> queryOderDetail())
                        .setNegativeButton(R.string.common_cancel, null).show();
            }
        });
    }

    public void setJumpAct(JumpAct jumpAct){
        this.jumpAct = jumpAct;
    }

    public JumpAct getJumpAct(){
        return jumpAct;
    }

    private void successJumpAct(TransInfo info, String wxImageUrl) {
        if (jumpAct!=null){
            isClose =true;
            jumpAct.successJumpAct(info, wxImageUrl);
        }
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (!frmCtx.isFinishing()) {
                switch (msg.what) {
                    case 0:
                        if (count > 0) {
                            queryOder();
                            count--;
                        } else {
                            if (jumpAct != null) {
                                jumpAct.onTimeOut();
                            }
                        }
                        break;
                }
            }
        }
    };

    public void closeOrder(){
        L.d("调用微信关闭订单 "+orderId);
        isClose = true;
        if (!isDestroy){
            mHandler.removeMessages(0);
            RequestCallback.cancelAllRequest();
            L.d("在微信页面关单 停止查询 ");
        }
        if (TextUtils.isEmpty(orderId)){
            return;
        }
        params = new HashMap<>();
        params.put(UrlConstants.KEY_ACCOUNT, User.getInstance().getAccount());
        params.put(UrlConstants.KEY_POS_ID, User.getInstance().getPosId());
        params.put(UrlConstants.KEY_ORDER_ID, orderId);
        params.put(UrlConstants.KEY_CHANNEL_ID, "WX");
        RequestCallback.post(frmCtx, UrlConstants.QR_CODE_CLOSE_ORDER, params, new AbstractRequestCallback() {
            @Override
            public void onResponse(String response, int id) {

            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (!isClose){
            mHandler.removeMessages(0);
            RequestCallback.cancelAllRequest();
            isDestroy =true;
        }
    }
}
